import java.util.Stack;
/**
 * @author : WXY
 * @create : 2022-08-19 22:04
 * @Info : 获取栈中的最小值
 */
public class Code05_GetMinStack {
    public static class MyStack_1{
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;

        public MyStack_1() {
            this.stackData = new Stack<Integer>();
            this.stackMin = new Stack<Integer>();
        }

        public void push(int value) {
            if (stackMin.isEmpty()) {
                stackMin.push(value);
            } else if (value <= this.getmin()) {
                stackMin.push(value);
            }
            stackData.push(value);
        }

        public int pop() {
            if (stackData.isEmpty()) {
                throw new RuntimeException("栈空了 ");
            }
            int value = stackData.pop();
            if (value == stackMin.peek()) {
                 stackMin.pop();
            }
            return value;
        }
        public int getmin() {
            if (stackMin.isEmpty()) {
                throw new RuntimeException("栈空了====");
            }
            return stackMin.peek();
        }

    }

    public static class MyStack_2{
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;

        public MyStack_2() {
            stackData = new Stack<Integer>();
            stackMin = new Stack<Integer>();
        }

        public void push(int value) {
            if (stackMin.isEmpty()) {
                stackMin.push(value);
            } else if (value < getmin()) {
                stackMin.push(value);
            }else {
                int newMin = stackMin.peek();
                stackMin.push(newMin);
            }
        }

        public int pop() {
            if (stackData.isEmpty()) {
                throw new RuntimeException("栈空了");
            }
            stackMin.pop();
            return stackData.pop();
        }

        public int getmin() {
            if (stackMin.isEmpty()) {
                throw new RuntimeException("栈空了");
            }
            return stackMin.peek();
        }
    }
    public static void main(String[] args) {
        MyStack_1 stack1 = new MyStack_1();
        stack1.push(3);
        System.out.println(stack1.getmin());
        stack1.push(4);
        System.out.println(stack1.getmin());
        stack1.push(1);
        System.out.println(stack1.getmin());
        System.out.println(stack1.pop());
        System.out.println(stack1.getmin());

        System.out.println("=============");

        MyStack_2 stack2 = new MyStack_2();
        stack2.push(3);
        System.out.println(stack2.getmin());
        stack2.push(4);
        System.out.println(stack2.getmin());
        stack2.push(1);
        System.out.println(stack2.getmin());
        System.out.println(stack2.pop());
        System.out.println(stack2.getmin());
    }

}
